<?php

namespace yan\backendclient\controllers;

use Yii;
use yan\backendclient\models\Menu;
use yii\data\ArrayDataProvider;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * DefaultController implements the CRUD actions for Menu model.
 */
class DefaultController extends DebugController
{

    /**
     * Lists all Menu models.
     * @return mixed
     */
    public function actionIndex()
    {
        $list['pid'] = \yii::$app->request->get('pid',0);
        $list['id'] = Yii::$app->request->get('id',0);
        // 獲取父級分類信息
        if( !empty( $list['id'] )){
            $menu = Menu::find()->where(['id'=>$list['id']])->asArray()->one();
            $list['pid'] = $menu['pid'];
        }
    
        $query = Menu::find()->select(['c.*','(select count(*) from '.Menu::tableName().' where pid=c.id) as child'])
                ->from(Menu::tableName()." c")
                ->where(['pid'=>$list['pid']])
                ->orderBy('c.sort_order asc')
                ->asArray()->all();

        $dataProvider = new ArrayDataProvider([
            'allModels' => $query,
        ]);

        return $this->render('index', [
            'dataProvider' => $dataProvider,
            'list'=>$list,
        ]);
    }

    /**
     * Creates a new Menu model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new Menu();
        $model->loadDefaultValues();
        $model->pid = \Yii::$app->request->get('pid',0);
        
        $list['urlReferrer'] = \Yii::$app->request->referrer;

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $list['urlReferrer'] = Yii::$app->request->post('urlReferrer');
            if($model->doSave()){
                Yii::$app->getSession()->setFlash('message', Yii::t('debug', 'Successful'));
                return strpos($list['urlReferrer'], $this->action->id)==0 ? $this->redirect($list['urlReferrer']) : $this->redirect(['index', 'pid' => $model->pid]);
            }
            
        }
        return $this->render('create', [
            'model' => $model,
            'list' => $list,
        ]);
        
    }

    /**
     * Updates an existing Menu model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        $list['urlReferrer'] = \Yii::$app->request->referrer;

        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
            $list['urlReferrer'] = Yii::$app->request->post('urlReferrer');
            if($model->doSave()){
                Yii::$app->getSession()->setFlash('message', Yii::t('debug', 'Successful'));
                return strpos($list['urlReferrer'], $this->action->id)==0 ? $this->redirect($list['urlReferrer']) : $this->redirect(['index', 'pid' => $model->pid]);
            }
            
        }

        return $this->render('update', [
            'model' => $model,
            'list' => $list,
        ]);
        
    }

    /**
     * Deletes an existing Menu model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $ids = explode(',', $id);
        foreach ($ids as $id) {
            try {
                $model = $this->findModel($id);
                $counter = Menu::find()->where(['pid'=>$id])->count();
                if($counter > 0 ){
                    Yii::$app->getSession()->setFlash('message', Yii::t('debug', 'Has child data, Cannot remove data!'));
                }else{
                    $model->delete();
                    Yii::$app->getSession()->setFlash('message', Yii::t('debug', 'Successful'));
                }
            } catch (\Exception $e) {
                Yii::$app->getSession()->setFlash('message', $id.' Error : '.$e->getMessage());
            }
            
        }        
        
        return $this->redirect(['index', 'pid'=>$model->pid]);
    }

    /**
     * Finds the Menu model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Menu the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Menu::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.'.$id);
        }
    }
}
